package com.dlyk.util;


import org.springframework.util.ObjectUtils;

import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Supplier;

/**
 * @description:
 * @author: ajie
 * @date: 2024/7/18 18:42:59
 * @version: 1.0
 */
public class CacheUtils {
    
    /**
     * @description: 带有缓存的查询工具方法
     * @params: [cacheSelector, databaseSelector, cacheSave]       
     * @return: 
     * @author: ajie
     * @date: 2024/7/18 18:50
     */
    public static <T> T getCacheData(Supplier<T> cacheSelector, Supplier<T> databaseSelector, Consumer<T> cacheSave){
        //从redis查询
        T data = cacheSelector.get();
        //如果redis中没有值
        if (ObjectUtils.isEmpty(data)){
            //从数据库查
            data = databaseSelector.get();
            //数据库查到了数据
            if (!ObjectUtils.isEmpty(data)){
                //把数据放入redis
                cacheSave.accept(data);
            }
        }
        //返回数据
        return data;
    }
}
